package com.gl.multipleyes.api

import grails.converters.JSON
import com.gl.multipleyes.enums.InvitationStatus
import com.gl.multipleyes.*

class InvitationController {
	def returnList
	def brokerMessagingTemplate
	
	static namespace = "api"
	
	def index() {
		def user = null,
			userID = params.userId

		if (userID == null) {
			render Invitation.findAll() as JSON
		} else {
			if (!userID.toString().isNumber()) {
				render "Error"
			} else {
				user = User.findByExternalId(userID)
				render Invitation.findByUser(user) as JSON
			}
		}
	}

	def save(){
		
		
		def usie = Usie.get(params.usieId)
		println "invitations for Usie: " + params
		println "inviteds" + request.JSON
		println "request" + request
		//println "obj " + invitationInstances.toString() 
		
		if (!usie) {
			throw new Exception("Usie no existe")
		}
		
		returnList = Invitation.findAllByUsie(usie)
		
		def listInvited = []
		request.JSON.listInvited.each { userInstance ->
			if (!userInstance.externalId) {
				log.error("Usuario sin ID!!!!")
				return
			}
			def user = User.findByExternalId(userInstance.externalId)
			if (!user) {
				user = new User( userInstance )
				user.save(flush:true, failOnError: true)
			} 
			
			def invitation = new Invitation(user: user, usie: usie)
			returnList.add(invitation.save(flush : true, failOnError: true))
			
			def invited = [
				externalId : invitation.user.externalId,
			    invitationId : invitation.id,
			    invitationStatus : invitation.invitationStatus
			] as Object
			listInvited.add invited
		}
		//brokerMessagingTemplate.convertAndSend "/topic/invitation",  request.JSON 
		brokerMessagingTemplate.convertAndSend "/topic/invitation", [
			usieId : params.usieId,
			listInvited : listInvited
		]
		render returnList as JSON
	}
	def update(){
		println params
		println request.JSON
		def invitation = Invitation.get(params.id)
		if(request.JSON.invitationStatus){
			println "Es aceptado"
			invitation.setInvitationStatus(InvitationStatus.ACCEPTED)
		} else {
			println "Es rechazado"
			invitation.setInvitationStatus(InvitationStatus.REJECTED)
		}
		invitation.save(flush : true, failOnError: true)
//		println params.id.toString().concat(request.JSON.invitationStatus.toString())
		def invited = [
			externalId : invitation.user.externalId, 
			invitationId : params.id,
			invitationStatus : invitation.invitationStatus
		] as Object
		def listInvited = [ invited ] 			
		brokerMessagingTemplate.convertAndSend "/topic/invitation", [
			usieId : params.usieId, 
			listInvited : listInvited
		] 
		render "ok" 
		
	}
}
